package com.jz.community.moduleshopping.confirmOrder.payPop;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.baseGoods.ShopInfo;
import com.jz.community.basecomm.bean.enums.CodeType;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.net.rxandroid.OnLoadListener;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.confirmOrder.bean.OrderPayResultBean;
import com.jz.community.moduleshopping.confirmOrder.bean.SubmitOrderResultBean;
import com.jz.community.moduleshopping.confirmOrder.enums.OrderPayFormType;
import com.jz.community.moduleshopping.confirmOrder.model.ConfirmOrderModel;
import com.jz.community.moduleshopping.confirmOrder.model.ConfirmOrderModelImpl;
import com.jz.community.moduleshopping.confirmOrder.task.GetCardBalanceTask;
import com.jz.community.moduleshopping.confirmOrder.ui.NewConfirmOrderActivity;
import com.jz.community.moduleshopping.confirmOrder.ui.PayFailureActivity;
import com.jz.community.moduleshopping.integralGoods.ui.IntegralSuccessActivity;
import com.jz.community.moduleshopping.orderDetail.bean.OrderEvent;
import com.jz.community.moduleshopping.orderDetail.ui.OrderDetailActivity;
import com.jz.community.moduleshopping.orderList.task.GroupPaymentTask;

import org.greenrobot.eventbus.EventBus;

import cn.shequren.communityPeople.pay.bean.CardInfo;
import cn.shequren.communityPeople.pay.bean.PayEvent;
import cn.shequren.communityPeople.pay.constants.CommUnityPayConstants;
import cn.shequren.communityPeople.pay.utils.CommUnityPayUtil;
import io.reactivex.Observable;

/**
 * Created by Tony on 2018/4/5.
 * <p>
 * 支付弹窗
 */
public class NewCommPayPopUp extends PopupWindow {
    private ImageView buttonAlipay, buttonWechatPay, buttonBalance;
    private LinearLayout llAlipay, llWechatPay, llBalance;
    private TextView tvPayActuallyMoney, btnAtoncePopwindow, tvClosePopWindow, tvBalancePrice, tvBalanceDeficiency;
    private int selectPayType;
    private SubmitOrderResultBean resultBean;
    private String payPrice;
    private ShopInfo shopInfo;
    private Context context;
    private Observable<PayEvent> toPayRxBusObser;
    private ConfirmOrderModel confirmOrderModel;
    private int orderPayFromType; //支付来源
    private View payView;

    private GroupPaymentListener groupPaymentListener;


    public void setGroupPaymentListener(GroupPaymentListener groupPaymentListener) {
        this.groupPaymentListener = groupPaymentListener;
    }

    public interface GroupPaymentListener {
        void groupPaymentCallBack(int payResult);
    }

    public NewCommPayPopUp(Context context, String payPrice, int orderPayFromType) {
        payView = LayoutInflater.from(context).inflate(R.layout.module_shopping_choose_buy_type_popwindow, null);
        setContentView(payView);
        this.context = context;
        this.setHeight(RelativeLayout.LayoutParams.MATCH_PARENT);
        this.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        this.setFocusable(false);
        this.setOutsideTouchable(false);
        this.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(context, R.color.transparent)));
        this.setAnimationStyle(R.style.choose_repertory_anim);
        this.payPrice = payPrice;
        this.orderPayFromType = orderPayFromType;
        this.confirmOrderModel = new ConfirmOrderModelImpl(context);
        initView(payView);
        addListener();
        paymentCallback();
        getCardBalance();
    }

    /**
     * 支付价格
     *
     * @param payPrice
     */
    public void setPayPrice(String payPrice) {
        this.payPrice = payPrice;
        tvPayActuallyMoney.setText("¥" + payPrice);
    }

    /**
     * 店铺Info
     *
     * @param shopInfo
     */
    public void addShopInfo(ShopInfo shopInfo) {
        this.shopInfo = shopInfo;
    }

    private void initView(View view) {
        llAlipay = view.findViewById(R.id.ll_alipay);
        llBalance = view.findViewById(R.id.ll_balance);
        buttonAlipay = view.findViewById(R.id.button_alipay);
        llWechatPay = view.findViewById(R.id.ll_wechat_pay);
        buttonBalance = view.findViewById(R.id.button_balance);
        buttonWechatPay = view.findViewById(R.id.button_wechat_pay);
        btnAtoncePopwindow = view.findViewById(R.id.btn_atonce_popwindow);
        tvPayActuallyMoney = view.findViewById(R.id.tv_pay_actually_money);
        tvClosePopWindow = view.findViewById(R.id.tv_close_popWindow);
        tvBalancePrice = view.findViewById(R.id.tv_balance_price);
        tvBalanceDeficiency = view.findViewById(R.id.tv_balance_deficiency);
        tvPayActuallyMoney.setText("¥" + payPrice);
    }

    private void addListener() {
        llAlipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleAliPayType();
            }
        });
        llWechatPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleWwiXinPayType();
            }
        });
        llBalance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleBalancePayType();
            }
        });
        btnAtoncePopwindow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Preconditions.isNullOrEmpty(resultBean) && !Preconditions.isNullOrEmpty(resultBean.getBigOrder())) {
                    handlePayType(selectPayType);
                    dismiss();
                }
            }
        });
        tvClosePopWindow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (orderPayFromType == OrderPayFormType.PAY_FORM_TYPE_1.getPayFormType()) {
                    showCancelPayDialog();
                }else {
                    dismiss();
                }
            }
        });
        payView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (orderPayFromType == OrderPayFormType.PAY_FORM_TYPE_1.getPayFormType()) {
                        showCancelPayDialog();
                    }else {
                        dismiss();
                    }
                }
                return true;
            }
        });
    }

    private void handleAliPayType() {
        selectPayType = 1;
        buttonAlipay.setBackgroundResource(R.mipmap.choose_green_no);
        buttonWechatPay.setBackgroundResource(R.mipmap.choose_green_ok);
        buttonBalance.setBackgroundResource(R.mipmap.choose_green_ok);
    }

    private void handleWwiXinPayType() {
        selectPayType = 2;
        buttonWechatPay.setBackgroundResource(R.mipmap.choose_green_no);
        buttonAlipay.setBackgroundResource(R.mipmap.choose_green_ok);
        buttonBalance.setBackgroundResource(R.mipmap.choose_green_ok);
    }

    private void handleBalancePayType() {
        selectPayType = 3;
        buttonBalance.setBackgroundResource(R.mipmap.choose_green_no);
        buttonWechatPay.setBackgroundResource(R.mipmap.choose_green_ok);
        buttonAlipay.setBackgroundResource(R.mipmap.choose_green_ok);
    }


    /**
     * 处理支付类型
     *
     * @param selectPayType
     */
    private void handlePayType(int selectPayType) {
        switch (selectPayType) {
            case 1:
                selectedConfirmPayWay(resultBean.getBigOrder(), "Alipay", selectPayType);
                break;
            case 2:
                selectedConfirmPayWay(resultBean.getBigOrder(), "MicroMessenger", selectPayType);
                break;
            case 3:
                selectedConfirmPayWay(resultBean.getBigOrder(), "CardBagPay", selectPayType);
                break;
        }
    }

    /**
     * 选择支付方式
     *
     * @param payType
     * @param selectPayType 1 支付宝 2、微信 3、卡包 4、积分
     */
    public void selectedConfirmPayWay(String orderId, String payType, int selectPayType) {

        //拼团支付回调
        if (orderPayFromType == OrderPayFormType.PAY_FORM_TYPE_3.getPayFormType()) {
            new GroupPaymentTask((Activity) context, new ITaskCallbackListener() {
                @Override
                public void doTaskComplete(Object o) {
                    OrderPayResultBean orderPayResultBean = (OrderPayResultBean) o;
                    LoggerUtils.Log().i("拼团支付  " + JSON.toJSON(orderPayResultBean));
                    if (selectPayType == 3 && orderPayResultBean.getCode() == CodeType.RECODE_4.getCodeType()) {
                        WpToast.l(context, "支付成功");
                        groupPaymentListener.groupPaymentCallBack(orderPayResultBean.getCode());
                    } else {
                        if (!Preconditions.isNullOrEmpty(orderPayResultBean.getData())) {
                            goPayOrderWay(selectPayType, orderPayResultBean);
                        } else {
                            WpToast.l(context, orderPayResultBean.getMessage());
                        }
                    }
                }
            }).execute(orderId, payType, selectPayType + "");
        } else {

            confirmOrderModel.orderPay(orderId, payType, new OnLoadListener<OrderPayResultBean>() {
                @Override
                public void onSuccess(OrderPayResultBean orderPayResultBean) {
                    LoggerUtils.Log().i("电商支付 " + JSON.toJSON(orderPayResultBean));
                    if (!Preconditions.isNullOrEmpty(orderPayResultBean)) {
                        goPayOrderWay(selectPayType, orderPayResultBean);
                    } else {
                        WpToast.l(context, orderPayResultBean.getMsg());
                    }
                }

                @Override
                public void onFail(String s, int code) {

                }
            });
        }
    }

    /**
     * 订单支付方式
     *
     * @param selectPayType
     * @param orderPayResultBean
     */
    private void goPayOrderWay(int selectPayType, OrderPayResultBean orderPayResultBean) {
        switch (selectPayType) {
            case 1:
                CommUnityPayUtil.goPay((Activity) context, CommUnityPayConstants.REQUEST_CODE_SUCCESS, CommUnityPayConstants.PAY_METHOD_ALIPAY_SDK, CommUnityPayConstants.PAY_MEDIUM_APP, orderPayResultBean.getData());
                break;
            case 2:
                CommUnityPayUtil.goPay((Activity) context, CommUnityPayConstants.REQUEST_CODE_SUCCESS, CommUnityPayConstants.PAY_METHOD_WECHAT, CommUnityPayConstants.PAY_MEDIUM_APP, orderPayResultBean.getData());
                break;
            case 3:
                orderCardBagPayResult(selectPayType, orderPayResultBean);
                break;
            case 4:
                orderIntegralPayResult(selectPayType, orderPayResultBean);
                break;
        }
    }

    /**
     * 卡包余额
     */
    private void getCardBalance() {
        new GetCardBalanceTask((Activity) context, o -> {
            CardInfo cardInfo = (CardInfo) o;
            if (!Preconditions.isNullOrEmpty(cardInfo)) {
                tvBalancePrice.setText(AppConstants.MONEY + cardInfo.getAmount());
                if (ConverterUtils.toDouble(cardInfo.getAmount()) >= ConverterUtils.toDouble(payPrice)) {
                    SHelper.gone(tvBalanceDeficiency);
                    SHelper.vis(buttonBalance);
                    handleBalancePayType();
                } else {
                    SHelper.vis(tvBalanceDeficiency);
                    SHelper.gone(buttonBalance);
                    handleAliPayType();
                }
            } else {
                SHelper.vis(tvBalanceDeficiency);
                SHelper.gone(buttonBalance);
                handleAliPayType();
            }
        }).execute();
    }

    public void setConfirmPayOrder(SubmitOrderResultBean resultBean) {
        this.resultBean = resultBean;
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        super.showAtLocation(parent, gravity, x, y);
        setWindowAttributes(0.4f);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        setWindowAttributes(1f);
    }

    /**
     * 设置窗口透明度
     *
     * @param alpha
     */
    private void setWindowAttributes(float alpha) {
        WindowManager.LayoutParams params = ((BaseMvpActivity) context).getWindow().getAttributes();
        params.alpha = alpha;
        ((BaseMvpActivity) context).getWindow().setAttributes(params);
    }

    //支付完成回调
    @SuppressLint("CheckResult")
    private void paymentCallback() {
        toPayRxBusObser = RxBus.getInstance().register(PayEvent.toPayRxBusTag, PayEvent.class);
        toPayRxBusObser.subscribe(payEvent -> {
            //拼团支付回调
            if (orderPayFromType == OrderPayFormType.PAY_FORM_TYPE_3.getPayFormType()) {
                groupPaymentListener.groupPaymentCallBack(payEvent.getPayResult());
            } else {
                //支付成功回调
                int payResult = payEvent.getPayResult();
                if (payResult == CommUnityPayConstants.PAY_RESULT_SUCCESS) {
                    handleToPayState(0);
                } else if (payResult == CommUnityPayConstants.PAY_RESULT_CANCEL) {
                    handleToPayState(-1);
                } else if (payResult == CommUnityPayConstants.PAY_RESULT_ERROR) {
                    handleToPayState(-2);
                }
            }
        });
    }

    /**
     * 卡包支付回调
     *
     * @param orderPayResultBean
     */
    @SuppressLint("CheckResult")
    private void orderCardBagPayResult(int selectPayType, OrderPayResultBean orderPayResultBean) {
        if (selectPayType == 3 && orderPayResultBean.getCode() == CodeType.RECODE_1.getCodeType()) {
            WpToast.l(context, "支付成功");
            handleToPayState(0);
        } else {
            handleToPayState(-1);
        }
    }

    /**
     * 支付弹窗
     *
     * @param isPayPop
     */
    private void showPayLoadingPop(boolean isPayPop) {
        if (!((BaseMvpActivity) context).isFinishing()) {
            if (isPayPop) {
                ((NewConfirmOrderActivity) context).showPayLoading();
            } else {
                ((NewConfirmOrderActivity) context).dismissPayLoading();
            }
        }
    }

    /**
     * 积分支付回调
     *
     * @param orderPayResultBean
     */
    @SuppressLint("CheckResult")
    private void orderIntegralPayResult(int selectPayType, OrderPayResultBean orderPayResultBean) {
        if (selectPayType == 4 && orderPayResultBean.getCode() == CodeType.RECODE_1.getCodeType()) {
            WpToast.l(context, "兑换成功");
            toOrderPaySuccessActivity(resultBean.get_embedded().getOrderInfoList().get(0).getOrderId(), false);
        } else {
            WpToast.l(context, orderPayResultBean.getMessage());
        }
    }


    /**
     * 处理支付成功状态
     *
     * @param code
     */
    @SuppressLint("CheckResult")
    private void handleToPayState(int code) {
        if (code == CodeType.RECODE_1.getCodeType()) {
            if (!Preconditions.isNullOrEmpty(resultBean) && !Preconditions.isNullOrEmpty(resultBean.get_embedded())) {
                toOrderPaySuccessActivity(resultBean.get_embedded().getOrderInfoList().get(0).getOrderId(), true);
            } else {
                if (!Preconditions.isNullOrEmpty(resultBean) && !Preconditions.isNullOrEmpty(resultBean.getBigOrder())) {
                    toOrderPaySuccessActivity(resultBean.getBigOrder(), true);
                }
            }
        } else {
            if (!Preconditions.isNullOrEmpty(resultBean) && !Preconditions.isNullOrEmpty(resultBean.get_embedded())) {
                toOrderPayFailureActivity(resultBean.get_embedded().getOrderInfoList().get(0).getOrderId());
            } else {
                if (!Preconditions.isNullOrEmpty(resultBean) && !Preconditions.isNullOrEmpty(resultBean.getBigOrder())) {
                    toOrderPayFailureActivity(resultBean.getBigOrder());
                }
            }
        }
    }

    /**
     * 支付成功跳转
     *
     * @param orderId
     * @param isPayFromType
     */
    private void toOrderPaySuccessActivity(String orderId, boolean isPayFromType) {
        if (isPayFromType) {
            Intent intent = new Intent(context, OrderDetailActivity.class);
            intent.putExtra("orderId", orderId);
            context.startActivity(intent);
        } else {
            Intent intent = new Intent(context, IntegralSuccessActivity.class);
            intent.putExtra("orderId", orderId);
            intent.putExtra("sendType", shopInfo.getSendType());
            context.startActivity(intent);
        }
        handleOrderFinishUI(true);
    }

    /**
     * 支付失败跳转
     *
     * @param orderId
     */
    private void toOrderPayFailureActivity(String orderId) {
        WpToast.l(context, "支付失败");
        Intent intent = new Intent(context, PayFailureActivity.class);
        intent.putExtra("orderId", orderId);
        context.startActivity(intent);
        handleOrderFinishUI(true);
    }

    /**
     * 支付完成不同界面处理
     *
     * @param isRxPost
     */
    private void handleOrderFinishUI(boolean isRxPost) {

        if (isRxPost) {
            handleRxEventPost();
        }

        payPopUnregisterRx();
    }

    public void payPopUnregisterRx() {
        EventBus.getDefault().post(new AppEvent(EventConfig.ORDER_REFRESH));
        RxBus.getInstance().unregister(PayEvent.toPayRxBusTag, toPayRxBusObser);
    }

    /**
     * 更新订单列表
     */
    private void handleRxEventPost() {
        if (!((BaseMvpActivity) context).isFinishing()) {
            OrderEvent orderEvent = new OrderEvent();
            orderEvent.setOrderType(OrderEvent.ORDER_TYPE_1);
            RxBus.getInstance().post(orderEvent);
            if (orderPayFromType == OrderPayFormType.PAY_FORM_TYPE_1.getPayFormType()) {
                ((BaseMvpActivity) context).finish();
            }
        }
    }

    /**
     * 显示放弃付款弹窗
     */
    private void showCancelPayDialog() {
        new MaterialDialog.Builder(context)
                .title("确认放弃付款吗?")
                .content("订单会为您保留一段时间,请尽快支付")
                .positiveText("我要离开")
                .negativeText("继续支付")
                .negativeColor(ContextCompat.getColor(context,R.color.negative_color))
                .positiveColor(ContextCompat.getColor(context,R.color.positive_color))
                .onPositive((dialog, which) -> {
                    dismiss();
                    dialog.dismiss();
                    if (orderPayFromType == OrderPayFormType.PAY_FORM_TYPE_1.getPayFormType()) {
                        handleOrderFinishUI(true);
                        RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MODULE_SHOPPING_ORDER_LIST);
                    }else {
                        handleOrderFinishUI(false);
                    }
                })
                .onNegative((dialog, which) -> dialog.dismiss())
                .show();
    }

}


